package com.gw2.gw2world.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class ServerState implements Serializable, Comparable<ServerState> {
	private static final long serialVersionUID = 1L;
	public static final char STATE_CLOSED=0;
	public static final char STATE_OPEN=1;
	public static final char STATE_ATTACKING=2;
	public static final char STATE_DEFENDING=3;
	public int server_id=0;
	public String name="";
	public String state="Inactive";
	public List<Event> events=new ArrayList<Event>(10);
	public ServerState() {}
	/** Construct a copy without the events and the state
	 * @param ss Object to copy
	 */
	public ServerState(ServerState ss) {
		server_id=ss.server_id;
		name=ss.name;
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		result = prime * result + server_id;
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		ServerState other = (ServerState) obj;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (server_id != other.server_id)
			return false;
		return true;
	}
	@Override
	public int compareTo(ServerState be) {
		return server_id>be.server_id?1:0;
	}
	@Override
	public String toString() {
		return "BasicEvent [server_id=" + server_id + ", name=" + name + ", state=" + state + "]";
	}
	public char getState() {
		boolean failed=false, isLastEventSuccessful=false;
		for(Event e : events) {
			if(e.state.equals("Active") && (e.flag&8)==8 && e.depth==1) return STATE_DEFENDING;
			if(e.state.equals("Active")) return STATE_ATTACKING;
			if(e.state.equals("Fail") && (e.flag&8)==8 && e.depth==1) failed=true;
			if(e.state.equals("Success") && e.depth==1) isLastEventSuccessful=true;
		}
		if(!failed && isLastEventSuccessful) return STATE_OPEN;
		return STATE_CLOSED;
	}
}
